//
//  User.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/5/6.
//  Copyright © 2017年 zwj. All rights reserved.
//


import Foundation
import HandyJSON
import SwiftyJSON

class User: NSObject , HandyJSON {

    var phone: String = ""
    var name: String = ""
    var userId: String = ""//    @JsonProperty("id")
    var isLoggedIn: Bool = false
    var deviceToken = ""
    var bpushChannelId = ""
    var _tempChannel : String?
    var token = ""
    
    var nickname = ""
    
    var icon = ""
    
    var qq = ""
    var wx = ""
    var company = ""
    
    var position = ""
    var email = ""
    var birthday = ""
    
    var channels = ""
    
    var contacts = 0
    
//    var mainbusiness;
    
    /**
     * 0:未设置 1：男 2：女
     */
    var sex = 0
    
    static let get = User()
    
    internal override required init() {

    }
    
    func mapping(mapper: HelpingMapper) {
        mapper.specify(property:&userId, name: "id")
    }
    
    static func isLogin() -> Bool {
        return User.get.isLoggedIn
    }
    static func logout() -> Void {
        UserDefaults.standard.set("", forKey: "user")
        User.get.copyFrom(User.init())
        User.get.token = ""
        User.get.isLoggedIn = false
    }

    static func getToken() -> String? {
        return User.get.token
    }
    
    
    static func loginWithResult(_ response:[String:Any]) {
        
        let newUser = JSONDeserializer<User>.deserializeFrom(dict:response as NSDictionary)
        
        let user = User.get
//        user.phone = response["phone"] as! String
//        user.userId = String(response["id"] as! Int)
//        
//        user.nickname = response["nickname"] as! String
//        
//        user.icon = response["icon"] as! String
//        user.qq = response["qq"] as! String
//        user.wx = response["wx"] as! String
//        user.company = response["company"] as! String
//        user.position = response["position"] as! String
//        user.email = response["email"] as! String
//        user.birthday = response["birthday"] as! String
//        user.channels = response["channels"] as! String
//        user.contacts = response["contacts"] as! Int
//        user.sex = response["sex"] as! Int

        User.get.copyFrom(newUser)
        
        user.isLoggedIn = true
        
        user.persistent()
    }
    
    static func updateChannelId() {
        if !User.isLogin() {
            return
        }
        if let channle = User.get._tempChannel {
            User.get.bpushChannelId = channle
        }
        let params = ["bpushChannelId":User.get.bpushChannelId ,
                      "id":User.get.userId,
                      "pushType":"2"]
        _ = NetworkManager.GET(NetworkManager.PushChannelBind,params:params) { (status, response) in
            if(status){

            }
        }
    }
    
    static func setToken(_ token1:String) {
        User.get.token = token1
    }
    
    func update( _ callback:@escaping (Bool, WTMResponse)->Void = {_,_ in }) {
        if let temp = _tempChannel {
            self.bpushChannelId = temp
        }
//        let string = self.serialize();
        var serialized = self.toJSON() ?? [:]
//            JSONSerializer.serialize(model: self).toSimpleDictionary()!
        serialized["id"] = self.userId
        serialized.removeAll(keys: ["userId","_tempChannel","deviceToken","token","isLoggedIn","bpushChannelId"])
        var params = ["user":""]
        if let str = serialized.jsonString() {
            params = ["user":str]
        }
        
        _ = NetworkManager.POST(NetworkManager.UPDATE_USER , params : params) { (isSuccess, response) in
            
            callback(isSuccess,response)
            
            if isSuccess {
                User.loginWithResult(response.wtmDic)
            }
        }
    }
    
    func serialize() -> String {
//        let serialized = JSONSerializer.serialize(model: self)
//        let json = serialized.toJSON()!
//        return self.toJSONString() ?? ""
        
        if var anyObject = self.toJSON() {
            anyObject["userId"] = self.userId
            if JSONSerialization.isValidJSONObject(anyObject) {
                do {
                    let jsonData: Data = try JSONSerialization.data(withJSONObject: anyObject, options: [])
                    return String(data: jsonData, encoding: .utf8) ?? ""
                } catch _ {
                    return ""
                }
            } else {
                return ""
            }
        }
        return ""
    }
    
    func persistent() {
        let userStr = self.serialize()
        UserDefaults.standard.set(userStr, forKey: "user")
        
    }
    
    func fromPersistence() {

        guard let userStr = UserDefaults.standard.string(forKey: "user") else {
            return
        }
        guard let userJson = JSON.init(parseJSON: userStr).dictionaryObject else{
            return
        }
        
        let newUser = JSONDeserializer<User>.deserializeFrom(dict:userJson as NSDictionary)!
        newUser.userId = userJson["userId"] as! String
        User.get.copyFrom(newUser)
        User.setToken(newUser.token)
        User.get.isLoggedIn = true
    }
    
    func copyFrom(_ newUser : User?) {
        self.phone = (newUser?.phone)!
        self.userId = (newUser?.userId)!

        self.nickname = (newUser?.nickname)!
        self.icon = (newUser?.icon)!
        self.qq = (newUser?.qq)!
        self.wx = (newUser?.wx)!
        self.company = (newUser?.company)!
        self.position = (newUser?.position)!
        self.email = (newUser?.email)!
        self.birthday = (newUser?.birthday)!
        self.channels = (newUser?.channels)!
        self.contacts = (newUser?.contacts)!
        self.sex = (newUser?.sex)!
    }
}
